var _COLOR = (function() {
	var datafields =[
		{name: 'color_id', type: 'int'},
        {name: 'color_name'},
		{name: 'color_total', type: 'int'},
		{name: 'color_position', type: 'int'},
		{name: 'color_insert', type: 'date'},
		{name: 'color_category_type'}
	];
	var $this = this;
	var source,dataAdapter=null;
	return {
		onCommit: function(Params, Id,callback) {
            /* Commit data lên vào DB, Id>0 là Update, Id=0 hoặc ko có là Insert */
            backend({
                url: _CONFIG.COLOR_COMMIT_URI,
                data: {
                    Id: Id,
                    Params: Params
                },
                callback: function(rsdata) {
                    if (rsdata.result < 0) {
                        $.jGrowl(rsdata.message, {sticky: true, theme: 'growl-error', header: 'Error!'});
                    } else {
                        $.jGrowl(rsdata.message);
                        if (typeof callback == 'function') {
                            callback();
                        }
                    }
                }
            }).call();
        },
		creategrid:function(){
            
            source = {
                datatype: "json", type: "POST",
                datafields: datafields,
                url: _CONFIG.COLOR_BINDING_URI+_CONFIG.COLOR_TYPE,
                id:'color_id',
                root: 'rows',
            };
            dataAdapter = new $.jqx.dataAdapter(source, {
                loadError: function(xhr, status, error) {
                    bckdialog({type: 'error'}).open("<b>Status</b>:" + xhr.status + "<br/><b>ThrownError</b>:" + error + "<br/>", 'Error Message!');
                }
            });
            var columns = [
                {
                    text: '', dataField: 'color_id', width: 60, filterable: false, sortable: false,editable: false,
                    cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
                        var str = "";
                        if (value && value > 0) {
                            try {
                                //value = $.parseJSON(value);
                                str += "\
                                    <span style='margin: 4px 4px 4px 12px; float: left;' class=\"icon-pencil\" onclick=\"_COLOR.onEditItem(" + value + ");\"  title='Edit:" + value + "'></span>\
                                ";
                                str += "\
                                    <span style='margin: 4px; float: left;' class='icon-trash' onclick=\"_COLOR.onDeleteItem(" + value + ");\" title='Delete:" + value + "'></span>\
                                ";
                            } catch (e) {
                            }
                        }

                        return str;
                    }
                },
                {
                    text: 'NAME'       , dataField: 'color_name',minWidth: 220
                },
                {
                    text: 'POSITION'       , dataField: 'color_position'    ,
                    width: 60, cellsalign: 'right', 
                    filterable: false, sortable: false,editable: true,
                    columntype: 'numberinput', filtertype: 'number',
                    validation:function (cell, value) {
                        if (value < 0 || value > 99) {
                            return { result: false, message: "Position should be in the 0-99 interval." };
                        }
                        return true;
                    }
                },    
                {
                    text: 'TOTAL'       , dataField: 'color_total',width: 60,editable: false
                },
				{
                    text: 'TYPE'       , dataField: 'color_category_type',width: 60,editable: false
                },
                {
                    text: 'CREATE'        , dataField: 'color_insert'      , width: 120,  cellsformat: 'yyyy-MM-dd HH:mm:ss',
                    filterable: false, sortable: false,editable: false
                }
            ];
            
            $(_CONFIG.COLOR_JQXGRID).jqxGrid({
                width: '100%', //autoheight:true,
                //height: '100%',
                source: dataAdapter,
                theme: theme,
                columns: columns,
                selectionmode: 'singlecell',
                editmode: 'dblclick',
                editable: true,
                handlekeyboardnavigation: function(event)
                {
                    var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
                    if (key == 27) {
                        $this.cancel=true;
                    }
                },

            }).bind('cellbeginedit', function (event) {
                $this.cancel=false;
            }).bind('cellendedit', function (event) {
                /* Lưu dữ liệu khi chỉnh sửa trên lưới */
                if($this.cancel)return;
                /* Lưu dữ liệu khi chỉnh sửa trên lưới */
                try{
                    var args = event.args;
                    var column = args.datafield, _row = args.rowindex, _value = args.value;
                    var _data = $(_CONFIG.JQXGRID).jqxGrid('getrowdata', _row);
                    var _id = _data.Id;
                    if (_id == undefined || _id == "") {
                        return;
                    }
                    switch (column) {
                        case 'Title':
                            if (_value != _data.Title && _value!='')
                                _CP.onCommit({Title: _value}, _id);
                            break;
                        case 'Parent':
                            if (_value != _data.Parent)
                                _CP.onCommit({Parent: _value}, _id,function(){
                                    _CP.onRefresh();
                                });
                            break;
                        case 'Position':
                            if (_value != _data.Position)
                                _CP.onCommit({Position: _value}, _id);
                            break;
                        case 'Active':
                            if (_value)
                                _CP.onCommit({Active: 'true'}, _id);
                            else
                                _CP.onCommit({Active: 'false'}, _id);
                            break;
                        default:
                            $.jGrowl("Chưa mở tính năng sửa trực tiếp cột này", {sticky: true, theme: 'growl-error', header: 'Error!'});
                    }
                } catch (e) {
                    $.jGrowl(e.message, {sticky: true, theme: 'growl-error', header: 'Error!'});
                    //bckdialog({type:'error'}).open(e.message);
                }
            });
        },
		onInit  :   function(){
			if($('#dialog-color-gridview').length!==1){
				$.jGrowl('POPUP NOT FOUND', {sticky: true, theme: 'growl-error', header: 'Error!'});
				return;
			}
			this.creategrid();
			bckdialog({
                title:'COLOR',
                message:$('#dialog-color-gridview'),
                buttons: [
                    
					{
                        text    :'ADD',
                        class   :'base_button base_green base-small-border-radius',
                        click   : function() {
                            _COLOR.onAddItem();
                        }
                    },
					{
                        text    :'REFRESH',
                        class   :'base_button base-small-border-radius',
                        click   : function() {
                            _COLOR.onRefresh();
                        }
                    },
                    {
                        text    :'CLOSE',
                        class   :'base_button base_red base-small-border-radius',
                        click   : function() {
                            $(this).dialog("close");
                        }
                    }
                ]
            }).open();
            
			
        },
		onOpenPopup:function(){
			if(dataAdapter===null){
				this.onInit();
			}else{
				$('#dialog-color-gridview').dialog('open'); 
			}
			
		},
        onChangeSource:function(type){
			if(type===_CONFIG.COLOR_TYPE)return;
            _CONFIG.COLOR_TYPE=type;
            source.url= _CONFIG.COLOR_BINDING_URI+_CONFIG.COLOR_TYPE;
            this.onRefresh();
        },
		onRefresh:function(){
            $(_CONFIG.COLOR_JQXGRID).jqxGrid('updatebounddata');
        },
		onAddItem:function(){
            this.onEditItem(0);
        },
        onEditItem:function(Id){
            if (PENDING)
                return false;
            $('#dialog-edit-panel-color>.base-dialog-modal').html('<div class="base_loading" style="display: block;height: 60px"></div>');
            bckdialog({
                title:'COLOR',
                message:$('#dialog-edit-panel-color'),
                buttons: [
                    
					{
                        text    :'Done',
                        class   :'base_button base_green base-small-border-radius',
                        click   : function() {
                            _COLOR.onSave();
                        }
                    },
                    {
                        text    :'Close',
                        class   :'base_button base_red base-small-border-radius',
                        click   : function() {
                            $(this).dialog("close");
                        }
                    }
                ]
            }).open();
            backend({
                url         :   _CONFIG.COLOR_EDITPANEL_URI+_CONFIG.COLOR_TYPE,
                data        :   {
                    Id  :   Id
                },
                callback    :   function(rsdata){
                    if(rsdata.result<0){
                        $('#dialog-edit-panel-color>.base-dialog-modal').html('<span style="color:red">'+rsdata.message+'</span>');
                    }else{
                        $('#dialog-edit-panel-color>.base-dialog-modal').html(rsdata.htmlreponse);
                        $('#dialog-edit-panel-color').dialog('close').dialog('open'); 
						$('#_form_edit_panel_color select').select2();
                    }
                }
            }).call();
        },
        onSave:function(){
            if( $('#_form_edit_panel_color').validationEngine('validate') === false)return false;
            var Params=$('#_form_edit_panel_color').serializeObject();
            $("#dialog-edit-panel-color").parents('.ui-dialog').find('.dialog-pending').show();
            this.onCommit(Params,$('#Id').val(),function(){
                $("#dialog-edit-panel-color").parents('.ui-dialog').find('.dialog-pending').hide();
                _COLOR.onRefresh();
				_COLOR.onCancel();
            });
            return false;
        },
        onCancel:function(){
            $('#dialog-edit-panel-color').dialog('close');
        },
        onDeleteItem:function(Id){
            backend_delete(_CONFIG.COLOR_DELETE_URI,Id,function(){
                _COLOR.onRefresh();
            });
        }
	};
}());